<?php

namespace app\admin\library;

use Throwable;
use ba\Random;
use Endroid\QrCode\Color\Color;
use Endroid\QrCode\Encoding\Encoding;
use Endroid\QrCode\ErrorCorrectionLevel;
use Endroid\QrCode\QrCode;
use Endroid\QrCode\Label\Label;
use Endroid\QrCode\Logo\Logo;
use Endroid\QrCode\RoundBlockSizeMode;
use Endroid\QrCode\Writer\PngWriter;
use Intervention\Image\ImageManager;
use Intervention\Image\Drivers\Gd\Driver;
use Intervention\Image\Typography\FontFactory;
class EngineQrcode{

    public static function getQRcodeImage($engine){
        $param = Random::encode64($engine['ticket'],true);
        $url = 'https://mp.lifecloud.top/mpengine?e='.'HZ'.$param;
        $qrString = self::createQrcode($url);
        $manager = new ImageManager(new Driver());
        $fontPath = public_path().'static'. DIRECTORY_SEPARATOR .'fonts'.DIRECTORY_SEPARATOR.'zhttfs'.DIRECTORY_SEPARATOR.'1.ttf';
        $publicImage = public_path().'static'.DIRECTORY_SEPARATOR.'images'.DIRECTORY_SEPARATOR;
        $backendImg = $manager->read($publicImage.'wechat_backend.jpg');
        $qrcodeImg = $manager->read($qrString);
        $backendImg->place($qrcodeImg, 'top-left', 270, 600)->place($publicImage.'wechat_front.png', 'top-left', 0, 0)->text($engine['name'], 462, 1420, function (FontFactory $font)use ($fontPath) {
            $font->filename($fontPath);
            $font->size(50);
            $font->color('000');
            $font->stroke('fff', 1);
            $font->align('left');
            $font->valign('middle');
            $font->lineHeight(1.2);
            $font->angle(0);
            $font->wrap(510);
        })->save($publicImage.$engine['ticket'].'.jpg',progressive: true, quality: 60);
        return '/static/images/'.$engine['ticket'].'.jpg';
    }
    public static function createQrcode($content){
        $writer = new PngWriter();
        // Create QR code
        $qrCode = new QrCode(
            data: $content,
            encoding: new Encoding('UTF-8'),
            errorCorrectionLevel: ErrorCorrectionLevel::Low,
            size: 720,
            margin: 10,
            roundBlockSizeMode: RoundBlockSizeMode::Margin,
            foregroundColor: new Color(0, 0, 0),
            backgroundColor: new Color(255, 255, 255)
        );

        // Create generic logo
        $logo = new Logo(
            path: public_path().'static/images/qlogo.png',
            resizeToWidth: 100,
            punchoutBackground: false
        );

        $result = $writer->write($qrCode, $logo);
        return $result->getString();
    }
}